<?php

namespace app\admin\controller\goods;

use app\admin\model\image\Attachment;
use app\admin\model\User;
use app\common\controller\Backend;
use app\admin\model\goods\Brand as BrandModel;
use app\admin\validate\goods\Goods as GoodsValidate;
use fast\Pinyin;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use fast\Tree;

/**
 * 商品管理
 *
 * @icon fa fa-circle-o
 */
class Goods extends Backend
{

    /**
     * Goods模型对象
     * @var \app\admin\model\goods\Goods
     */
    protected $model = null;
    protected $checkUpdatetime = true;
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\goods\Goods;
        $this->BrandModel = new BrandModel();
        $this->view->assign('countnum', $this->model->count());
        $this->view->assign("brandlist", $this->BrandModel->getBrandlist());
        $this->view->assign("attributeList", $this->model->getAttributeList());
        $this->view->assign("freightList", $this->model->getFreightList());
        $this->view->assign("isMatchList", $this->model->getIsMatchList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("specTypeList", $this->model->getSpecTypeList());
        $this->view->assign("isNewList", $this->model->getIsNewList());
        $this->view->assign("isHotList", $this->model->getIsHotList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $params = $this->request->param('filter');

        $params = json_decode($params,true);
        if (!empty($params['status']) && $params['status'] != 0)
        {
            $status = $params['status'];

        }else{
            $status = 0;
        }

        $this->assignconfig('sta',empty($status) ? 0 : $status);
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();

            $list = $this->model
                ->with(['en'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $row) {
                $row->getRelation('en')->visible(['name']);
            }
            $result = ['total' => $list->total(), 'rows' => $list->items()];
            return json($result);
        }

        $az_unit = User::where('condition',1)->sum('unit_number');
        $dl_unit = User::where('condition',2)->sum('unit_number');
        $unit_number = User::sum('unit_number');

        $this->view->assign('az_unit',$az_unit);
        $this->view->assign('dl_unit',$dl_unit);
        $this->view->assign('unit_number',$unit_number);
        return $this->view->fetch();
    }

    /**
     * @return array|string
     * @throws \think\Exception
     * 添加
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $list = $this->get_models_list(0, '');
            $categoryList = $this->get_category_list(0,'');
            $this->view->assign('toplist', $list);
            $this->view->assign('categoryList', $categoryList);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');

        $partnumber   = $this->model->where('partnumber|manufacturer',$params['partnumber'])->find();
        $manufacturer = $this->model->where('partnumber|manufacturer',$params['manufacturer'])->find();

        if (!empty($partnumber))
        {
            $this->error('零件号已存在,请勿重复添加');
        }
        if (!empty($manufacturer))
        {
            $this->error('厂家号已存在,请勿重复添加');
        }

        $shuff_image = explode(',',$params['shuff_image']);
        $params['main_image'] = $shuff_image[0];
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        $params['is_match'] = '0';
//        生成商品编号
        $params['goods_number'] = date('YmdHis');
        $GoodsValidate = new GoodsValidate();

        if (!$GoodsValidate->check($params)) {
            $this->error($GoodsValidate->getError());
        }

        if ($params['models_id'])
        {
            $model_id  = explode(',',$params['models_id']);
            $modelname = '';
            foreach($model_id as $v){
                if ($v != 0)
                {
                    $modelname .=$this->model_name($v).',';
                }
            }
            $modelname = substr($modelname,0,-1);
            $modelname = explode(',',$modelname);
            $params['models_name'] = implode(',',array_unique($modelname));
        }

        $result = false;
        Db::startTrans();
        try {
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $params['create_time'] = time();
            $result = $this->model->allowField(true)->save($params);
            $goods_id = $this->model->id;
            $this->model->category($goods_id,$params,0);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }

        $this->success();

    }

    private function get_full_name($id, $title = '')
    {
        $find = db('vehicle')->where('id', $id)->field('pid,mergename')->find();
        if ($find) {
            if ($find['pid'] > 0) {
                $title = $find['mergename'] . '/' . $title;
                return $this->get_full_name($find['pid'], $title);
            } else {
                return $find['mergename'] . '/' . $title;
            }
        } else {
            return $title;
        }
    }

    private function get_category_name($id, $title = '')
    {

        $find = db('goods_category')->where('id', $id)->field('pid,name')->find();

        if ($find) {
            if ($find['pid'] > 0) {
                $title = $find['name'] . '/' . $title;
                return $this->get_category_name($find['pid'], $title);
            } else {


                return $find['name'] . '/' . $title;
            }
        } else {
            return $title;
        }
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {

            $goods_addcategory = Db::name('goods_addcategory')
                ->where('gid',$row['id'])
                ->where('status',0)
                ->select();

            $vehicleArray  = [];
            $categoryArray = [];
            foreach($goods_addcategory as $key => $value)
            {
                if (!in_array($value['vehicle_id'],$vehicleArray))
                {
                    $vehicleArray[] = $value['vehicle_id'];
                }

                if (!in_array($value['category_id'],$categoryArray))
                {
                    $categoryArray[] = $value['category_id'];
                }
            }

            $row['models_id']   = implode(',',$vehicleArray);
            $row['modelId']     = $row['models_id'];

            $models_ids = explode(',', $row['models_id']);
            $m = [];
            foreach ($models_ids as $id) {
                $m[] = [
                    'id'    => $id,
                    'title' => trim($this->get_full_name($id),'/')
                ];
            }
            $row['models_id'] = $m;

            $cate_dataId = implode(',',$categoryArray);
            $row['categoryId']     = $cate_dataId;
            $row['category_id']    = $cate_dataId;
            $categorys = explode(',',$row['category_id']);
            $p = [];
            foreach ($categorys as $categoryId){
                $p[] = [
                    'id' => $categoryId,
                    'title' => trim($this->get_category_name($categoryId),'/')
                ];
            }
            $row['categoryIds']     = '';
            $row['modelsIds']       = '';
            $row['category_id']     = $p;
            $row['category_ids']    = [];
            $row['models_ids']      = [];

            if ($row['category_status'] == 1)
            {

                $cate_datas = Db::name('goods_addcategory')
                    ->where('gid',$row['id'])
                    ->where('status',1)
                    ->select();
                $vehiclesArray  = [];
                $categorysArray = [];
                foreach($cate_datas as $cateDatakey => $cateDataval)
                {                    if (!in_array($cateDataval['vehicle_id'],$vehiclesArray))
                {
                    $vehiclesArray[] = $cateDataval['vehicle_id'];
                }

                    if (!in_array($cateDataval['category_id'],$categorysArray))
                    {
                        $categorysArray[] = $cateDataval['category_id'];
                    }
                }


                $cate_dataIds = implode(',',$categorysArray);

                $row['categoryIds']  = $cate_dataIds;
                $row['category_ids'] = $cate_dataIds;
                $categorys = explode(',',$row['category_ids']);

                $ps = [];
                foreach ($categorys as $categoryId){
                    $ps[] = [
                        'id' => $categoryId,
                        'title' => trim($this->get_category_name($categoryId),'/')
                    ];
                }
                $row['category_ids'] = $ps;

                $goods_addcategorys = implode(',',$vehiclesArray);

                $row['models_ids'] = $goods_addcategorys;
                $row['modelsIds']  = $goods_addcategorys;

                $models_ids_a = explode(',', $row['models_ids']);
                $ms = [];
                foreach ($models_ids_a as $id) {
                    $ms[] = [
                        'id'    => $id,
                        'title' => trim($this->get_full_name($id),'/')
                    ];
                }
                $row['models_ids'] = $ms;
            }

            $this->view->assign('row', $row);
            $list = $this->get_models_list(0, '');
            $categorylist = $this->get_category_list(0, '');
            $this->view->assign('toplist', $list);
            $this->view->assign('categoryList', $categorylist);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');

        $partnumber   = $this->model->where('partnumber|manufacturer',$params['partnumber'])->where('id','neq',$ids)->find();

        if (!empty($partnumber))
        {
            $this->error('零件号已存在,请勿重复添加');
        }

        $shuff_image = explode(',',$params['shuff_image']);
        $params['main_image'] = $shuff_image[0];

        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;

        if ($params['models_id'])
        {
            $model_id  = explode(',',$params['models_id']);
            $modelname = '';
            foreach($model_id as $v){
                if ($v != 0)
                {
                    $modelname .=$this->model_name($v).',';
                }
            }
            $modelname = substr($modelname,0,-1);
            $modelname = explode(',',$modelname);
            $params['models_name'] = implode(',',array_unique($modelname));
        }
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $params['update_time'] = time();
            $result = $row->allowField(true)->save($params);

            $this->model->category($ids,$params,1);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");

        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                Db::name('goods_item')->where('goods_id', $item->id)->delete();
                Db::name('goods_addcategory')->where('gid', $item->id)->delete();
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

    private function get_category_list($pid,$key)
    {
        $model = db('goods_category');
        $model->where('pid', $pid)->where('del',0);

        if ($key) {
            $model->where('name', 'like', "%{$key}%");
        }
        $list = $model->field('id,name,level')->order('weigh desc, id desc')->select();
        $ids = [];
        foreach ($list as $v)
        {
            $ids[] = $v['id'];
        }
        $count = db('goods_category')->where('pid', 'in', $ids)->where('del', 0)
            ->group('pid')->column('count(pid)', 'pid');
        foreach ($list as &$v) {
            $v['child'] = $count[$v['id']] ?? 0;
        }
        return $list;
    }


    private function get_models_list($pid, $key)
    {
        $model = db('vehicle');
        $model->where('pid', $pid)->where('del', 0);

        if (mb_strlen($key) == 1 && preg_match("/^[a-zA-Z\s]+$/",$key))
        {
            $model->where('first', 'like', "%{$key}%");
        }else{
            $model->where('mergename', 'like', "%{$key}%");
        }

        $list = $model->field('id,mergename,first,level')->order('first asc,mergename desc')->select();

        $ids = [];
        foreach ($list as $v) {
            $ids[] = $v['id'];
        }

        $count = db('vehicle')
            ->where('pid', 'in', $ids)
            ->where('del', 0)
            ->group('pid')->column('count(pid)', 'pid');

        foreach ($list as &$v) {
            $v['child'] = $count[$v['id']] ?? 0;
        }

        if ($list[0]['level'] == 2)
        {
            foreach ($list as $key => $val)
            {
                preg_match_all('/[\x{4e00}-\x{9fa5}a-zA-Z0-9]/u' , $val['mergename'],$result);
                $name = implode('',$result[0]);
                $name = Pinyin::get($name);
                $list[$key]['pinyin'] = $name;
                $sort[] = $name;
            }
            array_multisort($sort, SORT_ASC, $list);
        }

        return $list;
    }

    public function getmodelslist()
    {
        $pid = $this->request->get('pid/d', 0);
        $key = $this->request->get('key');
        $list = $this->get_models_list($pid, $key);
        return json($list);
    }

    public function getcategoryslist()
    {
        $pid = $this->request->get('pid/d', 0);
        $key = $this->request->get('key');
        $list = $this->get_category_list($pid, $key);
        return json($list);
    }

    public function shelves($ids = '')
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->param("ids");
        $status = $this->request->param('status',0);
        // dump($status);
        // die;
        if (empty($ids)) $this->error('缺少参数');
        $this->model->where('id','in',$ids)->update(['status' => $status]);

        $this->success('操作成功');
    }

    /**
     * 车型名称
     */
    public function model_name($models_id)
    {
        $vehicle = Db::name('vehicle')->where('id',$models_id)->find();
        if ($vehicle['level'] == 1)
        {
            $mergename = Db::name('vehicle')->where('pid',$models_id)->column('mergename');
            $mergename = implode(',',$mergename);
            return $mergename;
        }elseif ($vehicle['level'] == 2){
            return $vehicle['mergename'];
        }else{
            return $this->model_name($vehicle['pid']);
        }

    }

}
